package com.ying.service;

import com.ying.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liujunjie
 * @Description description
 * @Note Hope we enjoy ourselves everday:)
 * @Date 2024-03-03 11:10
 **/

public class IpCountService {
    @Autowired
    private IpProperties ipProperties;
    @Autowired
    private HttpServletRequest request;
    private Map<String , Integer> map = new ConcurrentHashMap<>();
    public void  count(){
        String ip =request.getRemoteAddr();
        System.out.println("----------------"+ip );
        if (map.containsKey(ip)) {
            int count =map.get(ip);
            map.put(ip,++count);
        }else {
            map.put(ip,1);
        }
    }
    @Scheduled(cron="0/#{ipProperties.cycle} * * * * ?")
    public void print(){
        System.out.println("IP访问监控");
        if(ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())){
            System.out.println("|------Ip-address------|-----count-----|");
            for( Map.Entry<String, Integer> entry :map.entrySet()){
                System.out.println(String.format("|%20s  |%13d  |", entry.getKey() ,entry.getValue()));
            }
            System.out.println("|----------------------|---------------|");
        }else{
            System.out.println("|------Ip-address------|");
            for(  String key :map.keySet()){
                System.out.println(String.format("|%20s  |", key));
            }
            System.out.println("|----------------------|");
        }
        if(ipProperties.getCycleReset()){
            map.clear();
        }
    }

    public static void main(String[] args) {
        IpCountService ipCountService = new IpCountService();
        ipCountService.print();
    }
}
